import logo from '../../../public/images/logo.png';
import './index.less';
import React, { useEffect, useState } from 'react';
import { Avatar, Badge, Dropdown, Form, Input, MenuProps, message, Modal, Space } from 'antd';
import { Menu, Button } from 'antd';
import { history, useLocation } from 'umi';
import { Captcha, LoginAndRegister } from '@/types/login';
import { getCaptcha, register } from '@/service/api/login';
import { getUserInfo } from '@/service/api/user';
import { useSelector, useDispatch } from 'umi';
import { UserInfo } from '@/types/user';
import {
  ExclamationCircleOutlined,
  LoginOutlined,
  MessageOutlined,
  UserOutlined,
} from '@ant-design/icons';
import configs from '../../../config/env';
// const { Search } = Input;
const items: MenuProps['items'] = [
  {
    label: '首页',
    key: '/',
  },
  {
    label: '预定冒险',
    key: '/tours',
  },
  {
    label: '社区',
    key: '/feed',
  },
  {
    label: '国家',
    key: '/countries',
  },
  {
    label: '城市',
    key: '/cities',
  },
  {
    label: '要做的事情',
    key: '/things-to-do',
  },
  {
    label: '博客',
    key: '/blog',
  },
];
const Headers: React.FC = () => {
  const { pathname } = useLocation();
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [captchaImg, setCaptchaImg] = useState<Captcha>();
  const [regBtnLoading, setRegBtnLoading] = useState<boolean>(false);
  // 用户信息
  const userInfo = useSelector(
    (state: { userInfoModel: { userInfo: UserInfo } }) => state.userInfoModel.userInfo,
  );
  const isLogin = useSelector(
    (state: { userInfoModel: { isLogin: boolean } }) => state.userInfoModel.isLogin,
  );
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  // 退出登录
  const logout = () => {
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定要退出登录吗',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        localStorage.removeItem('token');
        message.success('已退出登录');
        dispatch({ type: 'userInfoModel/updateLoginState', isLogin: false });
        if (
          history.location.pathname.includes('/user-center') ||
          history.location.pathname.includes('/hold') || 
          history.location.pathname.includes('/msg-detail')
        ) {
          message.warning('请先登录');
          history.replace('/login');
        }
      },
    });
  };
  const dropdownItem: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <>
          <UserOutlined style={{ marginRight: 6, fontSize: 16 }} />
          <a rel="noopener noreferrer" href="/user-center" style={{ fontSize: 14 }}>
            个人中心
          </a>
        </>
      ),
    },
    {
      key: '2',
      label: (
        <>
          <MessageOutlined style={{ marginRight: 6, fontSize: 16 }} />
          <a rel="noopener noreferrer" href="/user-center?tab=message" style={{ fontSize: 14 }}>
            我的私信
          </a>
        </>
      ),
    },
    {
      key: '3',
      label: (
        <div style={{ color: 'red' }}>
          <LoginOutlined style={{ marginRight: 6, fontSize: 16 }} onClick={logout} />
          <a rel="noopener noreferrer" onClick={logout} style={{ fontSize: 14, color: 'red' }}>
            退出登录
          </a>
        </div>
      ),
    },
  ];
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  const onClick: MenuProps['onClick'] = (e) => {
    console.log('click ', e);
    history.push(e.key);
  };
  const toLogin = () => {
    history.push('/login');
  };
  const toHold = () => {
    history.push('/hold');
  };
  const showRegister = () => {
    setIsModalOpen(true);
    getCaptchaImage();
  };
  const onFinish = async (values: LoginAndRegister) => {
    // console.log('Success:', values);
    // console.log('uuid', captchaImg?.uuid);
    try {
      setRegBtnLoading(true);
      const res: any = await register({
        ...values,
        uuid: captchaImg?.uuid,
      });
      if (res) {
        message.success({
          content: res.msg,
          duration: 5,
        });
        handleCancel();
      }
    } catch (err: any) {
      // console.log(err.message);
      if (err.message === '验证码已失效') {
        getCaptchaImage();
        form.setFieldsValue({
          captcha: '',
        });
        return;
      }
      if (err.message === '验证码错误') {
        getCaptchaImage();
        form.setFieldsValue({
          captcha: '',
        });
        return;
      }
    } finally {
      setRegBtnLoading(false);
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  // const onSearch = (value: string) => console.log(value);
  const getCaptchaImage = async () => {
    const res: Captcha = await getCaptcha();
    setCaptchaImg(res);
  };
  // 获取用户信息
  const getUserInfoData = async () => {
    if (localStorage.getItem('token')) {
      const { data }: { data: UserInfo } = await getUserInfo();
      dispatch({ type: 'userInfoModel/updateUserInfo', userInfo: data });
      dispatch({ type: 'userInfoModel/updateLoginState', isLogin: true });
    }
  };
  useEffect(() => {
    getUserInfoData();
  }, []);

  return (
    <div className="header">
      <Modal
        title="注册"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
        centered
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 5 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          size="middle"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            style={{ flex: 1 }}
            label="验证码"
            name="code"
            rules={[{ required: true, message: '请输入验证码!' }]}
          >
            <Input />
          </Form.Item>
          <div className="captchaItem">
            <img
              style={{ marginLeft: 100 }}
              src={'data:image/gif;base64,' + captchaImg?.img}
              alt=""
              onClick={getCaptchaImage}
            />
            <Button
              type="link"
              onClick={() => {
                history.push('/login');
              }}
            >
              已有账号?去登录
            </Button>
          </div>
          <Form.Item style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button
                type="primary"
                htmlType="submit"
                style={{ width: 300 }}
                loading={regBtnLoading}
              >
                注册
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      <div className="header_container">
        <div className="left">
          <div
            className="logo_wrapper"
            onClick={() => {
              history.push('/');
            }}
          >
            <div className="logo">
              <img src={logo} alt="" />
            </div>
            <span className="logo_text">探险之旅</span>
          </div>
          {/* style={{ minWidth: 0 }} 导航响应式 */}
          <div className="menu_container">
            <Menu onClick={onClick} selectedKeys={[pathname]} mode="horizontal" items={items} />
          </div>
        </div>
        <div className="right">
          {/* <Search
          placeholder="搜索"
          allowClear
          onSearch={onSearch}
          style={{ width: 300, marginRight: 14 }}
        /> */}
          {isLogin && (
            <div style={{ marginRight: 20, cursor: 'pointer' }}>
              <Dropdown
                menu={{ items: dropdownItem }}
                placement="bottom"
                arrow={{ pointAtCenter: true }}
              >
                {/* <Badge count={1}> */}
                  {userInfo.avatar ? (
                    <Avatar
                      size={40}
                      src={configs[process.env.API_ENV as any].API_SERVER + userInfo.avatar}
                    />
                  ) : (
                    <Avatar size={40} src="/images/cat.e69c9c17.jpg" />
                  )}
                {/* </Badge> */}
              </Dropdown>
            </div>
          )}
          {!isLogin && (
            <>
              <Button type="primary" ghost onClick={toLogin}>
                登录
              </Button>
              <Button type="link" onClick={showRegister}>
                注册
              </Button>
            </>
          )}

          <div>
            <Button type="primary" onClick={toHold}>
              举办探险活动
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Headers;
